<template>
  <div class="song_contaner padd100">
    <el-row :gutter="20">
      <el-col :lg="20" style="margin-bottom:20px">
        <div class="song_warpper">
          <div class="left_song_img">
            <img :src="playlist.coverImgUrl + '?param=260y260'" alt="">
          </div>
          <div class="right_song_info">
            <div class="song_title">
              <el-tag>歌单</el-tag>
              <h1>{{playlist.name}}</h1>
            </div>
            <div class="song_desc">
              <div class="song_list_author">
                <div class="left_author_avatar">
                  <img :src="playlist.creator.avatarUrl + '?param=40y40'" alt="">
                </div>
                <div class="right_author_info">
                  <el-link type="primary"
                    @click="()=>{router.push({name:'user-home',params:{id:playlist.creator.userId}})}">
                    {{playlist.creator.nickname}}</el-link>
                  <span class="time">{{dayjs(playlist.createTime).format('YYYY-MM-DD')}} 创建</span>
                </div>
              </div>
            </div>
            <div class="r_m_opea">
              <el-button type="primary" :icon="VideoPlay" @click="play">播放</el-button>
              <el-button type="primary" :icon="Plus" @click="addPlayList">添加到播放列表</el-button>
              <el-button type="primary" :icon="FolderAdd" @click="collection" :loading="collectionBtnLoading"
                :disabled="playlist.subscribed?true:false">
                收藏 <span v-if="playlist.subscribedCount>0">({{playlist.subscribedCount}})</span>
                <!-- {{playlist.subscribed?'取消收藏':'收藏'}} -->
              </el-button>
              <el-button :icon="Comment" @click="handleClickScrollToComment">评论 <span v-if="playlist.commentCount>0">
                  ({{playlist.commentCount}})</span></el-button>
            </div>
            <div class="list_tag">
              <span class="text">标签：</span>
              <el-tag type="info" v-for="(item,index) in playlist.tags" :key="index" style="margin: 0 10px 10px 0"
                class="cursor_class" @click="handleClickTagItem(item)">{{item}}</el-tag>
            </div>
            <div class="text_muted">
              {{playlist.description}}
            </div>
          </div>
        </div>
        <div class="list_table_wrapper">
          <div class="top_b_m_tit">
            <div class="left_tit">
              <div>歌曲列表</div>
              <span>{{playlist.trackCount}}首歌</span>
            </div>
            <div class="right_play_count">
              <span>播放：<span>{{playlist.playCount}}</span>次</span>
            </div>
          </div>
        </div>
        <div>
          <MusicTable :tracks="playlist.tracks" />
        </div>
        <div class="see_more_container">
          <p>查看更多内容，请下载客户端</p>
          <a href="https://music.163.com/#/download" target="_blank">
            <el-button round type="primary">立即下载</el-button>
          </a>
        </div>
        <div class="comment_wrapper" id="comment">
          <div class="top_b_m_tit" style="margin-top:50px">
            <div class="left_tit">
              <div>评论</div>
              <span>共{{playlist.commentCount}}条评论</span>
            </div>
          </div>
          <div>
            <CommentComponent :id="Number(id)" @getTotal="getTotal" :playlistLimit="20" :pageNum="pageNum"
              :isActiveId="false" />
          </div>
          <div class="pageination_center" style="margin-top:40px">
            <el-pagination background layout="prev, pager, next" :total="total" v-show="total > 0"
              v-model:currentPage="pageNum" :page-size="20" @current-change="handleCurrentChange" />
          </div>
        </div>
      </el-col>
      <el-col :lg="4">
        <div class="right_other_container">
          <!-- 热门歌单 -->
          <div class="have_music_list">
            <div class="ohter_title">
              热门歌单
            </div>
            <div class="music_item" v-for="item in playlists" :key="item.id">
              <div class="left_img cursor_class" @click="handleClickRelatedItem(item.id)">
                <img :src="item.coverImgUrl + '?param=50y50'" alt="">
              </div>
              <div class="right_info">
                <div class="top_title cursor_class text_ellipsis text_decoration"
                  @click="handleClickRelatedItem(item.id)">{{item.name}}</div>
                <div class="bottom_by cursor_class text_ellipsis">
                  by <span class="text_decoration"
                    @click="()=>{router.push({name:'user-home',params:{id:item.creator.userId}})}">{{item.creator.nickname}}</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 相似歌曲 -->
          <div class="like_music_list">
            <div class="ohter_title">
              喜欢这个歌单的人
            </div>
            <div class="like_music_item">
              <div class="like_user_avatar cursor_class" v-for="item in subscriber" :key="item.userId"
                @click="()=>{router.push({name:'user-home',params:{id:item.userId}})}">
                <img :src="item.avatarUrl + '?param=45y45'" alt="" :title="item.nickname">
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <Collection ref="collectionRef" />
    <!-- 登录注册弹窗 -->
    <LoginAndRegister ref="loginAndRegisterRef" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRaw, toRefs, isRef, isReactive, watch } from "vue"
import { Headset, Plus, Timer, VideoPlay, Comment, FolderAdd, Pointer, PriceTag, House, Sunny, Guide, MostlyCloudy } from '@element-plus/icons-vue'
import CommentComponent from "@/components/Comment/index"
import { getPlayListDetail, getRelatedPlaylist, getPlaylistSubscribers, getPlaylistSubscribe } from "@/api/playlist";
import { useRoute } from "vue-router";
import { ElMessage } from 'element-plus'
import router from '@/router';
import dayjs from "dayjs";
import MusicTable from "@/components/MusicTable";
import { useStore } from "vuex";
import LoginAndRegister from '@/components/LoginAndRegister/index'
import { loginAndRegisterTypeRef } from "@/types/login";
const loginAndRegisterRef = ref<loginAndRegisterTypeRef | null>()
const store = useStore();
const route = useRoute()
// 路由参数
let id = route.params.id
const total = ref(0)
const pageNum = ref(1)
// 是否收藏
const collectionT = ref<number>(1)
const collectionBtnLoading = ref<boolean>(false)
// 详情数据
const playlistDetailData = reactive<any>({
  playlist: {
    creator: {}
  },
})
// 相关推荐歌单数据
const relatedPlaylistData = reactive<any>({
  playlists: [{ creator: {}, }]
})
const playlistSubscribers = reactive<any>({
  subscriber: []
})
const { playlist } = toRefs(playlistDetailData)
const { playlists } = toRefs(relatedPlaylistData)
const { subscriber } = toRefs(playlistSubscribers)
// 点击评论跳转指定位置
const handleClickScrollToComment = () => {
  document.getElementById('comment')?.scrollIntoView()
}
// 获取歌单详情数据
const getPlayListDetailData = async () => {
  let cookie = localStorage.getItem('cookie')
  const res: any = await getPlayListDetail({
    id: Number(id),
    // 带cookie可以检测用户是否收藏过该歌单
    cookie
  })
  playlist.value = res.playlist
  // playlistDetailData.playlist = res.playlist
}
/**
 * 获取相关歌单推荐数据
 */
const getRelatedPlaylistData = async () => {
  const res: any = await getRelatedPlaylist({ id })
  relatedPlaylistData.playlists = res.playlists
}
const handleCurrentChange = (val: number) => {
  pageNum.value = val
}
const getTotal = (val: number) => {
  total.value = val
}
const handleClickTagItem = (tagStr: string) => {
  router.push('/discover/playlist?tag=' + tagStr)
}
/**
 * 相关歌单点击事件
 */
const handleClickRelatedItem = (id: string) => {
  router.push({
    name: 'play-list-detail',
    params: {
      id
    }
  })
}
/**
 * 收藏歌单
 */
const collection = async () => {
  let cookie = localStorage.getItem('cookie')
  if (cookie) {
    try {
      collectionBtnLoading.value = true

      // if (playlistDetailData.playlist.subscribed) {
      //   collectionT.value = 2
      // } else {
      //   collectionT.value = 1
      // }
      // !!!! t: 类型取消收藏用不了 直接写死算了 直接收藏禁用按钮 全部去我的歌单那里删除歌单
      const res: any = await getPlaylistSubscribe({
        t: collectionT.value,
        id,
        cookie
      })
      ElMessage({
        message: "收藏成功!",
        type: 'success',
        duration: 5000,
      })
      getPlayListDetailData()
      // playlistDetailData.playlist.subscribed = true
    } catch (err: any) {
      console.log(err);
      if (err.code === 501) {
        ElMessage({
          message: "请勿重复收藏!",
          type: 'error',
          duration: 5000,
        })
      }
    } finally {
      collectionBtnLoading.value = false
    }
  } else {
    if (loginAndRegisterRef.value) {
      console.log(loginAndRegisterRef.value.loginVisible);
      loginAndRegisterRef.value.loginVisible = true
      loginAndRegisterRef.value.getQrKeyData()
    }
  }

}
/**
 * 获取歌单收藏者
 */
const getPlaylistSubscribersData = async () => {
  const res: any = await getPlaylistSubscribers({
    id,
    limit: 15
  })
  playlistSubscribers.subscriber = res.subscribers
}
if (id) {
  getPlayListDetailData()
  getRelatedPlaylistData()
  getPlaylistSubscribersData()
} else {
  ElMessage({
    message: "参数错误",
    type: 'error',
    duration: 2000,
    onClose: () => {
      history.go(-1)
    }
  })
}
watch(() => router.currentRoute.value.path, (newValue, oldValue) => {
  console.log('路由变化了哦');
  // location.reload()
  id = route.params.id
  if (id && router.currentRoute.value.name === 'play-list-detail') {
    getPlayListDetailData()
    getRelatedPlaylistData()
    getPlaylistSubscribersData()
  }
})
// 播放
const play = () => {
  let list = filterMusicData()
  store.dispatch('playAll', { list });
}
// 添加到播放列表
const addPlayList = () => {
  let list = filterMusicData()
  store.dispatch('addList', { list });
}
// 把需要vip的过滤出去
const filterMusicData = (): any[] => {
  let list = playlist.value.tracks.filter((item: any)=>{
    return item.fee != 1
  })
  return list
}
onMounted(() => {
})
</script>
<style lang="scss" scoped>
.song_contaner {
  margin-top: 20px;

  .song_warpper {
    display: flex;

    .left_song_img {
      width: 260px;
      height: 260px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right_song_info {
      padding-left: 40px;
      flex: 1;

      .song_title {
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        h1 {
          margin: 0;
          font-size: 24px;
          color: #333;
          margin-left: 14px;
        }
      }

      .song_desc {
        .song_list_author {
          display: flex;
          align-items: center;

          .left_author_avatar {
            width: 40px;
            height: 40px;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .right_author_info {
            margin-left: 20px;

            .time {
              margin-left: 20px;
              color: #999;
              font-size: 12px;
            }
          }
        }
      }

      .list_tag {
        margin-top: 14px;

        .text {
          font-weight: 700;
          color: #666;
          font-size: 12px;
        }
      }

      .r_m_opea {
        margin-top: 20px;

        button {
          margin-bottom: 10px;
          margin-left: 0;
          margin-right: 10px;
        }
      }
    }
  }

  .list_table_wrapper {
    margin-top: 40px;

    .top_b_m_tit {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2px solid #409eff;
      padding-bottom: 10px;

      .left_tit {
        color: #333;
        font-size: 20px;
        display: flex;

        span {
          color: #666;
          font-size: 12px;
          margin-top: 10px;
          margin-left: 14px;
        }
      }

      .right_play_count {
        span {
          color: #666;
          font-size: 12px;

          span {
            color: #409eff;
            font-weight: 700;
          }
        }
      }
    }
  }

  .see_more_container {
    display: flex;
    align-items: center;
    flex-direction: column;
    margin: 30px 0 0;

    p {
      color: #333;
      font-size: 13px;
    }
  }

  .comment_wrapper {
    .top_b_m_tit {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2px solid #409eff;
      padding-bottom: 10px;

      .left_tit {
        color: #333;
        font-size: 20px;
        display: flex;

        span {
          color: #666;
          font-size: 12px;
          margin-top: 10px;
          margin-left: 14px;
        }
      }
    }
  }

  .right_other_container {
    .have_music_list {
      .music_item {
        display: flex;
        margin: 14px 0;

        .left_img {
          width: 50px;
          height: 50px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .right_info {
          padding: 4px 0;
          padding-left: 10px;
          flex: 1;
          overflow: hidden;

          .top_title {
            font-size: 14px;
            margin-bottom: 10px;
          }

          .bottom_by {
            font-size: 12px;
            color: #999;

            span {
              color: #666;
            }
          }
        }
      }
    }

    .like_music_list {
      margin-top: 40px;

      .like_music_item {
        display: flex;
        flex-wrap: wrap;

        .like_user_avatar {
          width: 45px;
          height: 45px;
          margin: 8px;
          margin-left: 0;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }
    }

    .ohter_title {
      font-weight: 700;
      font-size: 12px;
      color: #333;
      border-bottom: 1px solid #ccc;
      padding-bottom: 10px;
    }
  }
}
</style>
